﻿using System;
using System.Linq;
using DAL.Engine;
using DAL.Engine.Interface;
using NHibernate;
using System.Collections.Generic;
using DAL.Nhibernate.Interface;

namespace DAL.Nhibernate.Repository
{
    public abstract class NhibernateRepository<TEntity, TKey> : IRepository<TEntity, TKey>
    where TEntity : IEntity<TKey>
    {
        protected readonly ISession _session;

        public NhibernateRepository(IConfigurationManager configurationManager)
        {
            _session = configurationManager.GetSession();
        }

        public TEntity Get(TKey id)
        {
            return _session.Get<TEntity>(id);
        }

        public IEnumerable<TEntity> GetAll()
        {
            return _session.QueryOver<object>().List<TEntity>();
        }

        public void Save(IEnumerable<TEntity> entities)
        {
            foreach (var e in entities)
            {
                _session.SaveOrUpdate(entities);
            }
        }

        public void Save(TEntity entity)
        {
            if (entity.IsNew)
            {
                _session.Save(entity);
            }
            else
            {
                _session.SaveOrUpdate(entity);
            }
        }

        public void Delete(TKey id)
        {
            _session.Delete(_session.Get<TEntity>(id));
        }
    }
}
